package cn.tedu.sentinel02.datasource;

import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.FileRefreshableDataSource;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;


import java.net.URL;
import java.util.List;

public class LocalDataSourceInit implements InitFunc {
    //加载json规则  实现初始化
    @Override
    public void init() throws Exception {
        ClassLoader classLoader =
                LocalDataSourceInit.class.getClassLoader();
        URL resource = classLoader.getResource("flowRules.json");
        String file = resource.getFile();
        System.out.println(file);

//        //线程  解析规则
//        ReadableDataSource<String, List<FlowRule>> dataSource =
//                new FileRefreshableDataSource<List<FlowRule>>(
//                        file, new Converter<String, List<FlowRule>>() {
//                    @Override
//                    public List<FlowRule> convert(String json) {
//                        List<FlowRule> flowRules = JSON.parseArray(json, FlowRule.class);
//                        System.out.println(flowRules);
//                        return JSON.parseArray(json,FlowRule.class);
//                    }
//                }
//                );
        //线程  解析规则
        ReadableDataSource<String, List<FlowRule>> dataSource =
                new FileRefreshableDataSource<List<FlowRule>>(
                        file, new Converter<String, List<FlowRule>>() {
                    @Override
                    public List<FlowRule> convert(String json) {
                        List<FlowRule> flowRules = JSON.parseArray(json, FlowRule.class);
                        System.out.println(flowRules);
                        return JSON.parseArray(json,FlowRule.class);
                    }
                }
                );
//加载规则
        System.out.println("111111111");
        System.out.println(dataSource);
        System.out.println(dataSource.getProperty());
        FlowRuleManager.register2Property(dataSource.getProperty());


    }
}
